// ==UserScript==
// @name         Ins 助手 of Rainbow
// @namespace    http://z.houbin.site/ins/
// @version      0.1
// @description  Instagram 视频，图片下载
// @author       Rainbow
// @match        *://www.instagram.com/*
// @grant        none
// ==/UserScript==

(function() {
	document.onreadystatechange = function() {
		if (document.readyState == "complete") {
			//添加下载按钮
			var article = document.querySelector('main article');
            let intervalHandler = setInterval(() => {
                article = document.querySelector('main article');
                if(article) 
                {
                    console.log('remove interval')
                    clearInterval(intervalHandler)
                }
            }, 2000);
			var button_download = document.createElement("button");
			button_download.innerText = "下载";
			button_download.style = "position:absolute;";
			button_download.onclick = function() {
// 				var medium = getMeta('medium');
// 				if (medium == 'image') {
// 					var sidecar = window._sharedData['entry_data'].PostPage[0]['graphql']['shortcode_media'][
// 						'edge_sidecar_to_children'
// 					];
// 					if (sidecar == undefined) {
// 						window.open(window._sharedData['entry_data'].PostPage[0]['graphql']['shortcode_media'].display_url);
// 					} else {
// 						var children = sidecar['edges'];
// 						for (var i = 0; i < children.length; i++) {
// 							var node = children[i];
// 							window.open(node.node.display_url);
// 						}
// 					}
// 				} else if (medium == 'video') {
// 					var video = window._sharedData['entry_data'].PostPage[0]['graphql']['shortcode_media'].video_url;
// 					window.open(video);
// 				}
                selfDownLoad(article);
			};
			article.appendChild(button_download);
		}
	}

	function getMeta(key) {
		var metas = document.getElementsByTagName("meta");
		for (var i = 0; i < metas.length; i++) {
			var meta = metas[i];
			if (meta.getAttribute('property') == key) {
				return meta.getAttribute('content');
			}
			if (meta.getAttribute('name') == key) {
				return meta.getAttribute('content');
			}
		};
		return null;
	}

    function selfDownLoad(article){
       let tempSelector = article.querySelector('div > div > div > div > img');
       window.open(tempSelector.getAttribute('src'));
    }
})();
